import { postRequest, uploadImage } from "./native/http";
import { getLocation, imagePicker, showHTkeyboard } from "./native/privacy";
import { liveFace } from "./native/ocr";
import { getCachingKeys, dropByCacheKey } from "react-router-cache-route";
import limitRequest from "./limitRequest";
import store from "../Redux/Store/Store";
import {
	openSelectAddress,
	openContactUI,
	getContacts,
	openPayView,
	closeModule,
	openAlipayView,
	callPhoneModule,
	openRepaymentAlipayView
} from "./native/navigate";
import {
	toast,
	getStatisticsDatas,
	TDAPPonEvent,
	settingPrivacy,
	platform,
	alertOneButt,
	alertTwoButt,
	getNativeInfo,
	environmentInfo,
	loactionInfo
} from "./base";
import { createPortal, getClassName } from "./utils";
import { mockUrl } from "@config/root";
/**
 * 网络请求
 */
function request(objs) {
	const appPlatFormData = store.getState().getAppPlatformsDatas;
	//正式，不要直接修改这些，在indexPage统一初始化吧
	let _root = appPlatFormData.httpUrl;
	if (process.env.ENV_CONFIG === "mock") {
		_root = mockUrl;
	}
	let _params = {
		url: _root + objs.url,
		header: {
			"Auth-Header": appPlatFormData.authHeaderStr
		},
		_alertShow: objs._alertShow != undefined ? objs._alertShow : false,
		params: objs.params
	};
	if (objs.imageArray && objs.imageArray.length > 0) {
		_params.imageArray = objs.imageArray;
		return uploadImage(_params);
	} else {
		return postRequest(_params);
	}
}

/**
 * 选择图片
 *
 * @param {*} objs
 */
function chooseImage(objs) {
	let _params = {
		type: objs.type,
		imageName: objs.imageName || `${new Date().getTime()}.png`,
		imageSize: objs.imageSize || 100 * 2014, // 图片大小 （0 表示不压缩，100*1024 表示 100Kb）
		thumbnailSize: objs.thumbnailSize || 10 * 1024 // 缩略图大小（0表示不压缩，不建议, 10*1024 表示 100Kb）
	};
	return imagePicker(_params);
}

/**
 * 活体检测
 *
 * @param {*} objs
 */
function startLiveFace(objs) {
	const appPlatFormData = store.getState().getAppPlatformsDatas;
	let _root = appPlatFormData.httpUrl; //正式，不要直接修改这些，在indexPage统一初始化吧
	let _params = {};
	_params.needUpload = objs.needUpload;

	_params.url = _root + objs.url;
	_params.header = {
		"Auth-Header": objs.header
	};
	_params.params = objs.params;
	_params.bizToken = objs.bizToken;

	return liveFace(_params);
}

/**
 * 设置状态栏
 */
function setStatusBarStyleLight(isLight) {
	if (platform() == "web") {
		return;
	}
	let params = {
		style: "white"
	};
	if (!isLight) {
		params.style = "black";
	}
	window.YHAuthorize.callHandler("Device_StatusBar", params, () => {});
}

/**
 * 保存图片
 */
function savePicture(picUrl) {
	return new Promise(function (resolve) {
		if (platform() == "web") {
			resolve();
		}
		let params = {
			url: picUrl
		};
		window.YHAuthorize.callHandler("SAVE_PICTURE", params, resp => {
			resolve(resp);
		});
	});
}

/**
 * @desc 函数防抖
 * @param func 函数
 * @param wait 延迟执行毫秒数
 */
function debounce(func, wait) {
	let timeout;
	return function () {
		let context = this;
		let args = arguments;
		if (timeout) clearTimeout(timeout);
		let callNow = !timeout;
		timeout = setTimeout(() => {
			timeout = null;
		}, wait);
		if (callNow) func.apply(context, args);
	};
}

/**
 * @desc 延时防抖函数。保证最后一次输入之后必须执行一次回调
 * @param func 函数
 * @param wait 延迟执行毫秒数
 */
//防抖方法
function delayDebounce(fn, ms) {
	let timeoutId;
	return function () {
		clearTimeout(timeoutId);
		timeoutId = setTimeout(() => {
			fn.apply(this, arguments);
		}, ms);
	};
}

/**
 * @desc 函数节流
 * @param func 函数
 * @param wait 延迟执行毫秒数
 */
function throttle(func, wait) {
	let previous = 0;
	return function () {
		let context = this;
		let args = arguments;
		let now = Date.now();
		if (now - previous > wait) {
			func.apply(context, args);
			previous = now;
		}
	};
}

function goodthrottle(fn, interval) {
	//上次触发的时间
	let lastTime = 0;
	let timer = null;
	return function () {
		//保存上下文的this
		const _that = this;
		//保存参数
		const args = arguments;
		//获取当前的时间
		let newDate = new Date();
		if (newDate - lastTime > interval) {
			fn.apply(_that, args);
			lastTime = newDate;
		} else {
			clearTimeout(timer);
			timer = setTimeout(() => {
				fn.apply(_that, args);
				lastTime = newDate;
			}, interval);
		}
	};
}

/**
 * 清除缓存
 */
function clearPageCache() {
	try {
		getCachingKeys().forEach(value => {
			dropByCacheKey(value);
		});
	} catch (error) {
		console.log("清除缓存报错");
	}
}

/**
 * 打电话
 */
function callPhone(params) {
	return callPhoneModule(params);
}

function getUrlParam(paraName) {
	let url = location.hash;
	let arrObj = url.split("?");
	if (arrObj.length > 1) {
		let arrPara = arrObj[1].split("&");
		let arr;
		for (let i = 0; i < arrPara.length; i++) {
			arr = arrPara[i].split("=");
			if (arr !== null && arr[0] == paraName) {
				return arr[1];
			}
		}
		return "";
	}
}

/**
 * 关闭页面
 */
function closePage(params) {
	return closeModule(params);
}

function setCoupon(objs) {
	if (platform() === "web") {
		return;
	} else {
		return new Promise(function (resolve) {
			window.YHAuthorize.callHandler("SET_COUPON", objs, res => {
				resolve(res);
			});
		});
	}
}
/**
 * 防抖
 */
function debounceNew(fun, delay) {
	return function (args) {
		let that = this;
		let _args = args;
		clearTimeout(fun.id);
		fun.id = setTimeout(function () {
			fun.call(that, _args);
		}, delay);
	};
}

/**
 * 手机号，身份证等加暗文
 */
function handelInfo(str, frontLen, endLen) {
	//str：要进行隐藏的变量  frontLen: 前面需要保留几位    endLen: 后面需要保留几位
	let len = str.length - frontLen - endLen;
	let xing = "";
	for (let i = 0; i < len; i++) {
		xing += "*";
	}
	return str.substring(0, frontLen) + xing + str.substring(str.length - endLen);
}

/**
 * 判断当前是否是小辉包环境进入
 */
function isXiaoHuiBao() {
	let getAppPlatformsDatas = sessionStorage.getItem("getAppPlatformsDatas")
		? JSON.parse(sessionStorage.getItem("getAppPlatformsDatas"))
		: {};
	return getAppPlatformsDatas.lnid === "1";
}

/**
 * 判断当前是否是小辉付环境进入
 */
function isXiaoHuiFu() {
	let getAppPlatformsDatas = sessionStorage.getItem("getAppPlatformsDatas")
		? JSON.parse(sessionStorage.getItem("getAppPlatformsDatas"))
		: {};
	return (
		getAppPlatformsDatas.lnid === "601" ||
		getAppPlatformsDatas.lnid === "602" ||
		getAppPlatformsDatas.lnid === "603" ||
		getAppPlatformsDatas.lnid === "604" ||
		getAppPlatformsDatas.lnid === "605" ||
		getAppPlatformsDatas.lnid === "606" ||
		getAppPlatformsDatas.lnid === "607" ||
		getAppPlatformsDatas.lnid === "608" ||
		getAppPlatformsDatas.lnid === "609" ||
		getAppPlatformsDatas.lnid === "610" ||
		getAppPlatformsDatas.lnid === "611" ||
		getAppPlatformsDatas.lnid === "614" ||
		getAppPlatformsDatas.lnid === "616" ||
		getAppPlatformsDatas.lnid === "617"
	);
}

/**
 * 判断当前是否是小辉贷环境进入
 */
function isXiaoHuiDai() {
	let getAppPlatformsDatas = sessionStorage.getItem("getAppPlatformsDatas")
		? JSON.parse(sessionStorage.getItem("getAppPlatformsDatas"))
		: {};
	return getAppPlatformsDatas.lnid === "802";
}

/**
 * html反转义
 * */
function htmlDecode(text) {
	let temp = document.createElement("div");
	temp.innerHTML = text;
	let output = temp.innerText || temp.textContent;
	temp = null;
	return output;
}

/**
 * 富文本转纯文本
 */
function htmlDecodeToText(text) {
	let htmlText = htmlDecode(text);
	htmlText = htmlText
		.replace(/<\/?.+?>/g, "")
		.replace(/\ +/g, "")
		.replace(/[\r\n]/g, "")
		.replace(/&nbsp;/gi, "")
		.replace("&nbsp;", "")
		.replace("&nsp;", "")
		.replace(/\s*/g, "");
	return htmlText;
}

/**比较版本号 */
function compareVersion(version1, version2) {
	const newVersion1 =
		`${version1}`.split(".").length < 3
			? `${version1}`.concat(".0")
			: `${version1}`;
	const newVersion2 =
		`${version2}`.split(".").length < 3
			? `${version2}`.concat(".0")
			: `${version2}`;
	//计算版本号大小,转化大小
	function toNum(a) {
		const c = a.toString().split(".");
		const numPlace = ["", "0", "00", "000", "0000"],
			r = numPlace.reverse();
		for (let i = 0; i < c.length; i++) {
			const len = c[i].length;
			c[i] = r[len] + c[i];
		}
		return c.join("");
	}

	//检测版本号是否需要更新
	function checkPlugin(a, b) {
		const numA = toNum(a);
		const numB = toNum(b);
		return numA > numB ? 1 : numA < numB ? -1 : 0;
	}
	return checkPlugin(newVersion1, newVersion2);
}

/**
 * @msg: 是否是高版本
 * @param {*}
 * @return {*}
 */
function isHigherVersion() {
	const { sdkVersionCode } = store.getState().getAppPlatformsDatas;
	return compareVersion(sdkVersionCode, "1.0.6") != -1;
}

/**通知生活支付结果 */
function noticePayResylt(params) {
	if (platform() !== "web") {
		//开发环境
		return new Promise(() => {
			window.YHAuthorize.callHandler(
				"FUN_NOTICE_LIFE_PAY_RESULT",
				params,
				() => {}
			);
		});
	}
}
/**支付成功 */
function noticePaySuccess(msg, isClose = true) {
	if (platform() !== "web") {
		//开发环境
		noticePayResylt({
			status: "0",
			msg
		});
		if (isClose) {
			closePage();
		}
	}
}
/**支付失败 */
function noticePayFailed(msg, isClose = true) {
	if (platform() !== "web") {
		//开发环境
		noticePayResylt({
			status: "1",
			msg
		});
		if (isClose) {
			closePage();
		}
	}
}
/**绑卡成功 */
function bindCardSuccess(msg, isClose = true) {
	if (platform() !== "web") {
		//开发环境
		noticePayResylt({
			status: "00",
			msg
		});
		if (isClose) {
			closePage();
		}
	}
}
/**绑卡失败 */
function bindCardFailed(msg, isClose = true) {
	if (platform() !== "web") {
		//开发环境
		noticePayResylt({
			status: "01",
			msg
		});
		if (isClose) {
			closePage();
		}
	}
}
/**支付取消 */
function noticePayCanceled(msg, isClose = true) {
	if (platform() !== "web") {
		//开发环境
		noticePayResylt({
			status: "2",
			msg
		});
		if (isClose) {
			closePage();
		}
	}
}

/**微信分享 */
function wxShareWebPage(params) {
	if (platform() !== "web") {
		//开发环境
		// window.YHAuthorize.callHandler("App_Share", params, () => {});
		return new Promise(function (resolve) {
			window.YHAuthorize.callHandler("App_Share", params, res => {
				console.log("分享回调来了 ----");
				resolve(res);
			});
		});
	}
}

/**微信支付 */
function wxPayWebPage(params) {
	if (platform() !== "web") {
		//开发环境

		return new Promise(function (resolve) {
			window.YHAuthorize.callHandler("App_wxPay", params, res => {
				resolve(res);
			});
		});
		// window.YHAuthorize.callHandler("App_wxPay", params, () => {});
	}
}

function noticeCheckoutPayResult(params) {
	if (platform() !== "web") {
		return new Promise(() => {
			window.YHAuthorize.callHandler(
				"FUN_NOTICE_CHECKOUT_RESULT",
				params,
				() => {}
			);
		});
	}
}

/**收银台支付成功 */
function noticeCheckoutPaySuccess(msg) {
	if (platform() !== "web") {
		//开发环境
		noticeCheckoutPayResult({
			status: "0",
			msg
		});
	}
}
/**收银台支付失败 */
function noticeCheckoutPayFailed(msg) {
	if (platform() !== "web") {
		//开发环境
		noticeCheckoutPayResult({
			status: "1",
			msg
		});
	}
}
/**收银台支付取消 */
function noticeCheckoutPayCancel(msg) {
	if (platform() !== "web") {
		//开发环境
		noticeCheckoutPayResult({
			status: "2",
			msg
		});
	}
}

//sdk 1.0.1以上版本才支持支付宝
function isSupportAlipay(version) {
	let num = Number(version.replace(/\./g, ""));
	console.log("sdk版本号：", version, "是否展示支付宝：", num > 101);
	if (num > 101) {
		return true;
	} else {
		return false;
	}
}
//原生sdk版本
function getSdkVersion(version) {
	let num = Number(version.replace(/\./g, ""));
	return num;
}
export default {
	isXiaoHuiFu,
	isXiaoHuiBao,
	isXiaoHuiDai,
	handelInfo,
	debounceNew,
	getUrlParam,
	goodthrottle,
	throttle,
	debounce,
	request: limitRequest(request),
	chooseImage,
	startLiveFace,
	setStatusBarStyleLight,
	getLocation,
	toast,
	platform,
	alertTwoButt,
	alertOneButt,
	settingPrivacy,
	getNativeInfo,
	savePicture,
	openSelectAddress,
	setCoupon,

	//talkingData
	TDAPPonEvent,
	getStatisticsDatas,

	environmentInfo,
	loactionInfo,
	clearPageCache,
	callPhone,
	openContactUI,
	getContacts,
	openPayView,
	closePage,
	delayDebounce,
	openAlipayView,
	showHTkeyboard,
	openRepaymentAlipayView,
	htmlDecodeToText,
	compareVersion,
	isHigherVersion,
	noticePayResylt,
	noticePaySuccess,
	noticePayFailed,
	noticePayCanceled,
	bindCardSuccess,
	bindCardFailed,
	wxShareWebPage,
	createPortal,
	getClassName,
	wxPayWebPage,
	noticeCheckoutPayResult,
	noticeCheckoutPaySuccess,
	noticeCheckoutPayFailed,
	noticeCheckoutPayCancel,
	isSupportAlipay,
	getSdkVersion
};
